import React,{useEffect,useRef} from 'react'
import { Button, Card, Form, Radio ,Select,message,Popconfirm} from 'antd'
import { EditOutlined,DeleteOutlined } from '@ant-design/icons';
import {useDispatch,useSelector} from 'react-redux'
import styles from './index.module.scss'
import { Breadcrumb } from 'antd'
import { Link, useNavigate } from 'react-router-dom'
import { ArticleStatus } from 'api/constants'
import { delArticle, getArticleList, getChannelList } from 'store/action/article'
import { DatePicker, Space,Table,Tag,Image } from 'antd';
import { useParams } from 'react-router-dom'
import locale from 'antd/es/date-picker/locale/zh_CN';
import 'moment/locale/zh-cn';
import img from 'assets/error.png'
const { RangePicker } = DatePicker;
const {Option} = Select


export default function Article() {
   const params1 = useParams()
   const isEdit = params1.id !== undefined
  const  navgite = useNavigate()
  const del = async (id) => {

    await dispatch(delArticle(id))
    // 重新发送请求
    await dispatch(getArticleList(params.current))
    message.success('删除成功')
  }


  //修改
  const handleEdit = (id) =>{
    console.log('id',id);
    navgite(`/home/publish/${id}`)
  }
  const columns = [
    
      {
        title: '封面',
        dataIndex: 'cover',
        render(cover) {
          if (cover.type === 0) {
            return <Image width={200} height={150} src={img}></Image>
          } else {
            return (
              <Image
                width={200}
                height={150}
                src={cover.images[0]}
                fallback={img}
              ></Image>
            )
          }
        }
      },
    {
      title: '标题',
      dataIndex: 'title',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (status) => {
        const obj = ArticleStatus.find((item) => item.id === status)
        return <Tag color={obj.color}>{obj.title}</Tag>
      }
    },
    {
      title: '发布时间',
      dataIndex: 'pubdate',
    },
    {
      title: '阅读数',
      dataIndex: 'read_count',
    },
    {
      title: '评论数',
      dataIndex: 'comment_count',
    },
    {
      title: '点赞数',
      dataIndex: 'like_count',
    },
    {
      title: '操作',
      dataIndex: 'id',
      render(id) {
        return (
          <Space>
            <Button shape="circle" type="primary" icon={<EditOutlined />} onClick={()=>handleEdit(id)}/>
            <Popconfirm title="确定要删除该文章吗？" onConfirm={() => del(id)}>
              <Button shape="circle" type="danger" icon={<DeleteOutlined />} />
            </Popconfirm>
          </Space>
        )
      }
    },
  
  ]
  //查询文章列表的参数
  const params = useRef({})
  const onFinish = (values) => {
    const { status, date, channel_id } = values
    status === -1
      ? delete params.current.status
      : (params.current.status = status)
    if (date) {
      params.current.begin_pubdate = date[0]
        .startOf('day')
        .format('YYYY-MM-DD HH:mm:ss')
      params.current.end_pubdate = date[1]
        .endOf('day')
        .format('YYYY-MM-DD HH:mm:ss')
    } else {
      delete params.current.begin_pubdate
      delete params.current.end_pubdate
    }
    params.current.channel_id = channel_id

    params.current.page = 1
    dispatch(getArticleList(params.current))
    console.log('values',values);
    console.log('d1',params.current);
  }
  const dispatch = useDispatch()
  const channels = useSelector((state) => state.article.channels)
  const articles = useSelector((state) => state.article.articles)
  useEffect(() => {
    dispatch(getChannelList())
    dispatch(getArticleList())
  }, [dispatch])

 

  const onChange = (page,pageSize) =>{
   
      params.current.page = page
      params.current.per_page = pageSize
      dispatch(getArticleList(params.current))
    
  }
  // console.log('channels',channels);
  // console.log('atricle',ArticleStatus);
  return (
    <div className={styles.root}>
      <Card
        title={
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>文章列表</Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        {/* 表单结构 */}
        <Form initialValues={{ status: -1 }} onFinish={onFinish}>
          <Form.Item label="状态" name="status">
            <Radio.Group >
              {ArticleStatus.map((item) =>
                <Radio key={item.id} value={item.id}>{item.title}</Radio>
              )}
            </Radio.Group>
          </Form.Item>

          <Form.Item label="频道" name="channel_id">
            <Select
              
              style={{
                width: 200,
              }}
              placeholder="请选择文章频道"
            >
              {channels.map((item)=>
              <Option key={item.id} value={item.id}>{item.name}</Option>
              )}
              
            </Select>
          </Form.Item>
          <Form.Item label="日期" name="date" >
          <RangePicker locale={locale}/>
          </Form.Item>
          <Form.Item>
            <Button type='primary' htmlType='submit'>筛选</Button> 
          </Form.Item>
        </Form>
      </Card>
      <Card title={`根据筛选条件共查询到${articles.total_count}条结果`}>
      <Table columns={columns} dataSource={articles.results} rowKey="id" 
        pagination={{
          total:articles.total_count,
          current:articles.page,
          pageSize:articles.per_page,
          onChange:onChange
          }}/>
      </Card>
    </div>
  )
}
